import uuid
from common import get_logger, session
import json
import time
from config import VOLC_APPID, VOLC_TOKEN

logger = get_logger(__name__)


def audio_to_text(audio_url):
    # 提交任务的地址
    submit_url = "https://openspeech.bytedance.com/api/v3/auc/bigmodel/submit"
    # 生成唯一的任务ID,用于标识本次的服务
    task_id = str(uuid.uuid4())
    # 构建HTTP请求头
    headers = {
        "X-Api-App-Key": VOLC_APPID,
        "X-Api-Access-Key": VOLC_TOKEN,
        "X-Api-Resource-Id": "volc.bigasr.auc",
        "X-Api-Request-Id": task_id,
        "X-Api-Sequence": "-1",
    }
    # 构建请求数据
    request_data = {
        "user": {"uid": "fake_uid"},
        "audio": {
            "url": audio_url,  # 音频文件URL地址
            "format": "mp3",  # 音频文件格式
            "codec": "raw",  # 音频编解码器
            "rate": 16000,  # 音频采样率
            "bits": 16,  # 音频位深度
            "channel": 1,  # 音频声道数
        },
        "request": {
            "model_name": "bigmodel",
            "show_utterances": True,
            "corpus": {"correct_table_name": "", "context": ""},
        },
    }
    # 向API发送请求，提交音频转文字的任务
    response = session.post(
        submit_url, data=json.dumps(request_data), headers=headers, timeout=10
    )
    if (
        "X-Api-Status-Code" in response.headers
        and response.headers["X-Api-Status-Code"] == "20000000"
    ):
        X_Tt_Logid = response.headers.get("X-Tt-Logid")
        logger.info(
            f"音频转文字任务提交成功，X_Tt_Logid：{X_Tt_Logid} 开始轮询结果......"
        )
        query_url = "https://openspeech.bytedance.com/api/v3/auc/bigmodel/query"
        # 复制请求头并添加日志ID
        query_headers = headers.copy()
        query_headers["X-Tt-Logid"] = X_Tt_Logid
        while True:
            query_response = session.post(
                query_url,
                json.dumps({}),
                headers=query_headers,
                timeout=10,
            )
            code = query_response.headers.get("X-Api-Status-Code")
            if code == "20000000":
                text = query_response.json()["result"]["text"]
                return text
            elif code == "20000001":
                logger.info(f"音频转文字任务正在处理中")
            else:
                logger.error(f"音频转文字任务查询失败,code:{code}")
            time.sleep(1)
    else:
        logger.error(f"音频转文字任务提交失败 ")
